#!/usr/bin/env bash
# Copyright (c) 2021-2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This script generates template for docs/PBC2IR.md
# 1. If PBC2IR.md already exists, it is copied to PBC2IR_OLD.md.
# 2. The new one PBC2IR.md is generated.
# 3. IR column is empty by default. PBC2IR_OLD.md is used to copy existing IR instructions to corresponds cells in PBC2IR.md.
# Another information isn't copied!

set -e

for ARGUMENT in "$@"; do
case "$ARGUMENT" in
    --binary-dir=*)
    PANDA_BINARY_ROOT="${ARGUMENT#*=}"
    ;;
    --root-dir=*)
    PANDA_ROOT="${ARGUMENT#*=}"
    ;;
esac
done

ISA=$PANDA_ROOT/isa/isa.yaml
DOC=$PANDA_ROOT/docs/PBC2IR.md
OLD_DOC=$PANDA_BINARY_ROOT/PBC2IR_OLD.md

[ -e "$OLD_DOC" ] && rm "$OLD_DOC"

[ -e "$DOC" ] && cp "$DOC" "$OLD_DOC" && rm "$DOC"

test "$DOC"

exec 1>"$DOC"

# Get signatures of all instructions
all_insts=$(grep "sig:" "$ISA" | cut -f2 -d':' | cut -f2 -d' ')
# Ignore repeated instructions
pbc_instructions=$(echo "$all_insts" | awk '{delete seen; c=0; for (i=1;i<=NF;i++) \
    if (!seen[$i]++) printf "%s%s", (++c>1?OFS:""), $i; print ""}')

echo "| PBC | IR |"
echo "|-----|----|"

for inst_name in $pbc_instructions; do
    descr=$(grep "| $inst_name |" "$OLD_DOC" | cut -f3 -d"|")
    echo "| $inst_name |$descr|"
done

echo
echo "This document generated by compiler/tools/pbc_2_ir_doc_gen.sh."

[ -e "$OLD_DOC" ] && rm "$OLD_DOC"
